/*
 * foxmob.cn has all rights reserved.
 */
package foxmob.mooc.user;
import foxmob.mooc.DbAccess;
import foxmob.mooc.Utils;
import foxmob.mooc.persist.tables.User;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import spark.Request;
import spark.Response;

import java.util.List;

import static spark.Spark.get;
import static spark.Spark.post;

//import me.chanjar.weixin.mp.api.
//import me.chanjar.weixin.mp.api.
//


/**
 *
 * @author liyusen
 */

public class UserAction {

    public static void  init(){
        post("/user/login",UserAction::login);
        post("/user/reg",UserAction::register);
        post("/user/update",UserAction::update);
        get("/user/logout",(req,res)->{
            req.session().attribute("name","");
            res.redirect("/",200);
            return "lg";
        });
        get("/users/get",UserAction::getUsers);

    }
    public static String login(Request req, Response res){




        String[] values = Utils.getMultipart(new String[]{"username","passwd"},req);
        if(values.length!=2) return "{\"id\":0}";
        try{
            DSLContext dsl = DbAccess.getDsl();

            List<SimpleUser> result = dsl
                    .select(User.USER.EMAIL,User.USER.NAME,User.USER.ID)
                    .from(User.USER).where(User.USER.USERNAME.equal(values[0]))
                    .and(User.USER.PASSWD.equal(values[1])).fetch().into(SimpleUser.class);

            for (SimpleUser r : result) {

                String s= String.format("%d",r.id);
                req.session(true);

                req.session().attribute("userid",s);

                res.cookie("user.id",s);
                res.cookie("user.name",r.name);
                res.cookie("user.email",r.email);
                req.session().attribute("userid",s);

                return String.format("{\"id\":%d,\"email\":\"%s\"}",r.id,r.email);
            }

        }catch(Exception e){
            e.printStackTrace();


        }



        return "0";
    }
    public static String register(Request req, Response res){

        String[] values = Utils.getMultipart(new String[]{"username","passwd","email"},req);

        if(values.length!=3) return "0";
        int n =0;


        try{

            DSLContext dsl = DbAccess.getDsl();

            Result<?> result = dsl.insertInto(User.USER,User.USER.USERNAME, User.USER.PASSWD,User.USER.EMAIL).
                    values(values[0],values[1],values[2]).
                    returning(User.USER.ID).fetch();
            for(Record r : result ){
                n = r.getValue(User.USER.ID);
                break;

            }


        }catch(Exception e){
            e.printStackTrace();


        }


        return String.format("{\"id\":%d}",n);
    }

    public static String getUsers(Request req, Response res){
        String rs = "[";
        int start = Integer.parseInt(req.queryParams("start"));
        int pgsize = Integer.parseInt(req.queryParams("pgsize"));
        String pattern = String.format("%s%s%s","%",req.queryParams("pattern"),"%");
        System.out.println(pattern);
        try{
            DSLContext dsl = DbAccess.getDsl();
            //Book Book.BOOK = new Book();
            Result<Record> result = dsl.select()
                    .from(User.USER).where(User.USER.USERNAME.like(pattern))
                    .or(User.USER.NAME.like(pattern))
                    .limit(pgsize).offset(start).fetch();

            for (Record r : result) {
                int userid = r.getValue(User.USER.ID);
                String name = r.getValue(User.USER.NAME);;
                String username = r.getValue(User.USER.USERNAME);
                String email = r.getValue(User.USER.EMAIL);
                String s = String.format("[%d,\"%s\",\"%s\",\"%s\"],",
                        userid,name,username,email);

                rs = String.format("%s%s",rs,s);
            }
            rs = String.format("%s[]]",rs);
            rs = String.format("{cnt:%d,result:%s}",8,rs);



        }catch(Exception e){
            e.printStackTrace();
            rs = "{cnt:0, result:[[]]}";

        }


        return rs;
    }
    public static String update(Request req, Response res){

        String[] values = Utils.getMultipart(new String[]{"id","name","username","email"},req);

        if(values.length!=4) return "0";
        int n =0;


        try{

            DSLContext dsl = DbAccess.getDsl();

            n = dsl.update(User.USER).set(User.USER.NAME,values[1])
                    .set(User.USER.USERNAME,values[2]).set(User.USER.EMAIL,values[3])
                    .where(User.USER.ID.equal(Integer.parseInt(values[0])))
                    .returning(User.USER.ID).fetchOne().getValue(User.USER.ID);


        }catch(Exception e){
            e.printStackTrace();


        }


        return String.format("{\"id\":%d,\"name\":\"%s\",\"username\":\"%s\",\"email\":\"%s\"}",
                n,values[1],values[2],values[3]);
    }

}
